package moni.anyou.com.view.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.LatLngBounds;
import com.amap.api.maps2d.model.Marker;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.json.JSONArray;
import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import moni.anyou.com.view.R;
import moni.anyou.com.view.amap.MapViewHelper;
import moni.anyou.com.view.amap.cluster.ClusterClickListener;
import moni.anyou.com.view.amap.cluster.ClusterOverlay;
import moni.anyou.com.view.amap.cluster.ClusterRender;
import moni.anyou.com.view.amap.cluster.demo.RegionItem;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.AppTools;
import moni.anyou.com.view.tool.PermissionTools;
import moni.anyou.com.view.widget.NetProgressWindowDialog;

import static moni.anyou.com.view.tool.DensityTools.dp2px;


public class RouteDetailActivity extends BaseActivity implements AMap.OnMapLoadedListener,View.OnClickListener {
    private AMap mAMap;
    private NetProgressWindowDialog window;
    MapView mapView;
    WebView web;
    private String currWebUrl = SysConfig.webUrl + "/m/routedetail.jsp?";
    private MapViewHelper mapViewHelper;
    private Map<Integer, Drawable> mBackDrawAbles = new HashMap<Integer, Drawable>();
    private String routeID = "0";
    //private ClusterOverlay mClusterOverlay;
    private LinearLayout ll_detail;
    private LinearLayout ll_restaurant;
    private LinearLayout ll_stay;
    private LinearLayout ll_scenicspot;
    private LinearLayout ll_culture;
    private LinearLayout ll_products;
    private LinearLayout ll_route_detail;
    private  LinearLayout ll_video;
    private LinearLayout ll_webview;
    private LinearLayout ll_detail_all;
    private LinearLayout ll_map;
    private ImageView iv_detail;
    private ImageView iv_video;
    private ImageView iv_restaurant;
    private ImageView iv_stay;
    private ImageView iv_scenicspot;
    private ImageView iv_culture;
    private ImageView iv_products;
    private TextView tv_route_routename;
    private TextView tv_route_contact;
    private TextView tv_route_equipment;
    private TextView tv_route_activityStrength;
    private TextView  tv_route_activityFee;
    //private TextView tv_change;
    private int isFullSCreen = 0;
    JSONArray routePointList;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_detail);
        initState();
        initWindow();
        initTitle();
        init();

        tvTitle.setText("路线详情");
        window = new NetProgressWindowDialog(mBaseActivity);
        routeID =  getIntent().getStringExtra("routeID");
        mapView = (MapView)findViewById(R.id.map_view);
        mapView.onCreate(savedInstanceState);
        mAMap=mapView.getMap();
        mAMap.getUiSettings().setZoomControlsEnabled(false);
        LogOut.getInstance().addActivity(this);
        // mLocalBroadcastManager = LocalBroadcastM
        mapViewHelper = new MapViewHelper(mapView);

        getInitInfo();


    }

    @Override
    public void initView() {
        ll_webview = (LinearLayout)findViewById(R.id.ll_webview);
        ll_detail_all =  (LinearLayout)findViewById(R.id.ll_detail_all);
        ll_map = (LinearLayout)findViewById(R.id.ll_map);
        ll_detail =  (LinearLayout)findViewById(R.id.ll_detail);
        ll_video =  (LinearLayout)findViewById(R.id.ll_video);
        ll_restaurant =  (LinearLayout)findViewById(R.id.ll_restaurant);
        ll_scenicspot =  (LinearLayout)findViewById(R.id.ll_scenicspot);
        ll_stay =  (LinearLayout)findViewById(R.id.ll_stay);
        ll_products =  (LinearLayout)findViewById(R.id.ll_products);
        ll_culture =  (LinearLayout)findViewById(R.id.ll_culture);
        ll_route_detail =  (LinearLayout)findViewById(R.id. ll_route_detail);
        iv_detail = findViewById(R.id.iv_detail);
        iv_restaurant = findViewById(R.id.iv_restaurant);
        iv_video = findViewById(R.id.iv_video);
        iv_scenicspot = findViewById(R.id.iv_scenicspot);
        iv_stay = findViewById(R.id.iv_stay);
        iv_products = findViewById(R.id.iv_products);
        iv_culture = findViewById(R.id.iv_culture);
        tv_route_routename =  (TextView)findViewById(R.id.tv_route_routename );
        tv_route_contact =  (TextView)findViewById(R.id.tv_route_contact);
        tv_route_equipment =  (TextView)findViewById(R.id.tv_route_equipment);
        tv_route_activityStrength =  (TextView)findViewById(R.id.tv_route_activityStrength);
        tv_route_activityFee = (TextView)findViewById(R.id.tv_route_activityFee);
        //tv_change = (TextView)findViewById(R.id.tv_change);
        web = (WebView) findViewById(R.id.webView);
        web.getSettings().setDefaultTextEncodingName("UTF-8");
        web.getSettings().setJavaScriptEnabled(true);
        web.setWebChromeClient(new WebChromeClient());
        //关闭缓存 功能
        web.getSettings().setAppCacheEnabled(false);
        web.getSettings().setAppCacheMaxSize(0);
        web.getSettings().setAppCachePath("");
        web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        web.getSettings().setDatabaseEnabled(false);
        web.setBackgroundColor(0);
        web.setFocusable(true);
        if (web != null) {
            web.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    window.closeWindow();
                }
            });

        }
        /*
        if (mAMap == null) {
            // 初始化地图
            mAMap = mapView.getMap();
            mAMap.setOnMapLoadedListener(this);
            //点击可以动态添加点
            mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
//                    double lat = Math.random() + 39.474923;
//                    double lon = Math.random() + 116.027116;
//
//                    LatLng latLng1 = new LatLng(lat, lon);
//                    RegionItem<String> regionItem = new RegionItem<String>(latLng1,
//                            "test");
//                    mClusterOverlay.addRegionItem(regionItem);

                }
            });
        }

       // mapViewHelper.drawLocationUI()
       */
    }
    public void loadUrl(String url) {
        if (web != null) {

            web.loadUrl(url);

        }
    }
    /*
    @Override
    public void onClick(Marker marker, List<RegionItem> RegionItems) {

        LatLngBounds.Builder builder = new LatLngBounds.Builder();
        for (RegionItem RegionItem : RegionItems) {
            builder.include(RegionItem.getPosition());
        }
        LatLngBounds latLngBounds = builder.build();
        mAMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 0)
        );
    }
    */
    private int getPixelsFromDp(int size){

        DisplayMetrics metrics =new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        return(size * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_left:
                onBack();
                break;
            case R.id.right_tv:
                break;
            case R.id.ll_detail:
                hideAll();
                ll_route_detail.setVisibility(View.VISIBLE);
                iv_detail.setVisibility(View.VISIBLE);
                ll_webview.setVisibility(View.GONE);
                break;
            case R.id.ll_video :
                hideAll();
                ll_route_detail.setVisibility(View.GONE);
                iv_video .setVisibility(View.VISIBLE);
                String webUrl = currWebUrl + "id="+routeID+"&key=video";
                loadUrl(webUrl);
                ll_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_restaurant :
                hideAll();
                ll_route_detail.setVisibility(View.GONE);
                iv_restaurant .setVisibility(View.VISIBLE);
                webUrl = currWebUrl + "id="+routeID+"&key=restaurant";
                loadUrl(webUrl);
                ll_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_stay:
                hideAll();
                iv_stay.setVisibility(View.VISIBLE);
                webUrl = currWebUrl  + "id="+routeID+"&key=stay";
                loadUrl(webUrl);
                ll_route_detail.setVisibility(View.GONE);
                ll_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_culture :
                hideAll();
                iv_culture.setVisibility(View.VISIBLE);
                ll_route_detail.setVisibility(View.GONE);
                webUrl =  currWebUrl  + "id="+routeID+"&key=culture";
                loadUrl(webUrl);
                ll_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_scenicspot:
                hideAll();
                iv_scenicspot.setVisibility(View.VISIBLE);
                ll_route_detail.setVisibility(View.GONE);
                webUrl =  currWebUrl  + "id="+routeID+"&key=scenicspot";
                loadUrl(webUrl);
                ll_webview.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_products :
                hideAll();
                iv_products.setVisibility(View.VISIBLE);
                ll_route_detail.setVisibility(View.GONE);
                webUrl = currWebUrl  + "id="+routeID+"&key=products";
                loadUrl(webUrl);
                ll_webview.setVisibility(View.VISIBLE);
                break;

           // case R.id.tv_change:
           //     if (isFullSCreen == 0) {
            //        ll_detail_all.setVisibility(View.GONE);
                    //ll_map.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
            //        isFullSCreen = 1;
                   // tv_change.setText("正常显示");
                    //mAMap=mapView.getMap();
                    //mAMap.getUiSettings().setZoomControlsEnabled(false);
                    //mapViewHelper.drawLocationUI(routePointList);

          //      }
            //    else{
            //        ll_detail_all.setVisibility(View.VISIBLE);
            //        ll_map.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,getPixelsFromDp(140)));
            //        isFullSCreen = 0;
            //        tv_change.setText("全屏");
            //    }
            //    break;
            default:
                break;
        }

    }
    private void hideAll(){
        iv_detail.setVisibility(View.GONE);
        iv_video .setVisibility(View.GONE);
        iv_restaurant .setVisibility(View.GONE);
        iv_scenicspot.setVisibility(View.GONE);
        iv_stay.setVisibility(View.GONE);
        iv_culture.setVisibility(View.GONE);
        iv_products.setVisibility(View.GONE);
    }
    @Override
    public void onMapLoaded() {



    }
    private Bitmap drawCircle(int radius, int color) {

        Bitmap bitmap = Bitmap.createBitmap(radius * 2, radius * 2,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        RectF rectF = new RectF(0, 0, radius * 2, radius * 2);
        paint.setColor(color);
        canvas.drawArc(rectF, 0, 360, true, paint);
        return bitmap;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
    /*
    @Override
    public Drawable getDrawAble(int clusterNum) {
        int radius = dp2px(getApplicationContext(), 80);
        if (clusterNum == 1) {
            Drawable bitmapDrawable = mBackDrawAbles.get(1);
            if (bitmapDrawable == null) {
                bitmapDrawable =
                        getApplication().getResources().getDrawable(
                                R.drawable.icon_openmap_mark);
                mBackDrawAbles.put(1, bitmapDrawable);
            }

            return bitmapDrawable;
        } else if (clusterNum < 5) {

            Drawable bitmapDrawable = mBackDrawAbles.get(2);
            if (bitmapDrawable == null) {
                bitmapDrawable = new BitmapDrawable(null, drawCircle(radius,
                        Color.argb(159, 210, 154, 6)));
                mBackDrawAbles.put(2, bitmapDrawable);
            }

            return bitmapDrawable;
        } else if (clusterNum < 10) {
            Drawable bitmapDrawable = mBackDrawAbles.get(3);
            if (bitmapDrawable == null) {
                bitmapDrawable = new BitmapDrawable(null, drawCircle(radius,
                        Color.argb(199, 217, 114, 0)));
                mBackDrawAbles.put(3, bitmapDrawable);
            }

            return bitmapDrawable;
        } else {
            Drawable bitmapDrawable = mBackDrawAbles.get(4);
            if (bitmapDrawable == null) {
                bitmapDrawable = new BitmapDrawable(null, drawCircle(radius,
                        Color.argb(235, 215, 66, 2)));
                mBackDrawAbles.put(4, bitmapDrawable);
            }

            return bitmapDrawable;
        }
    }
    */
    //手机高版本样式
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    private SystemBarTintManager tintManager;
    //手机高版本样式
    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.parseColor("#FEC600"));

            tintManager.setStatusBarTintEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(),
                        Color.TRANSPARENT);
            } catch (Exception e) {
            }
        }

    }
    @Override
    public void setAction() {
        super.setAction();
        ivBack.setOnClickListener(this);
        ll_detail.setOnClickListener(this);
        ll_restaurant.setOnClickListener(this);
        ll_video.setOnClickListener(this);
        ll_scenicspot.setOnClickListener(this);
        ll_stay.setOnClickListener(this);
        ll_products.setOnClickListener(this);
        ll_culture.setOnClickListener(this);
        //tv_change.setOnClickListener(this);
    }
    //得到路线详情
    public void getInitInfo() {
        window.ShowWindow();
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = "{\"cmd\":\"33\",\"uid\":\""+ SysConfig.uid + "\",\"token\":\""+ SysConfig.token+ "\",\"routeid\":\""+routeID+"\"}";
        params.put("sendMsg", cmdPara);
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {
                try {

                    JSONObject jsonObject = new JSONObject(t);
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        routePointList = ((JSONObject)jsonObject.getJSONArray("list").get(0)).getJSONArray("routePointList");
                        JSONArray routeInfo = ((JSONObject)jsonObject.getJSONArray("list").get(0)).getJSONArray("routeInfo");
                        tv_route_routename.setText(((JSONObject)routeInfo.get(0)).getString("routeInfo"));
                        tv_route_contact.setText(((JSONObject)routeInfo.get(0)).getString("linkMan")+" "+((JSONObject)routeInfo.get(0)).getString("linkMobile"));
                        tv_route_equipment.setText(((JSONObject)routeInfo.get(0)).getString("equipment"));
                        tv_route_activityStrength.setText(((JSONObject)routeInfo.get(0)).getString("activityStrength"));
                        tv_route_activityFee.setText(((JSONObject)routeInfo.get(0)).getString("activityFee"));
                        mapViewHelper.drawLocationUI(routePointList);

                    } else {
                        if (result == -2) {
                            AppTools.jumptoLogin(mBaseActivity, result);
                        }
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, ex.toString(), Toast.LENGTH_LONG).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();

                window.closeWindow();
            }
        });
    }


}
